/**
 *  created by lllwx
 *  date: 2021/10/26
 *  time: 4:13 下午
 *  version: 1.0
 *  desc:
 */
import {
  ref, watch, unref, isRef,
} from '@vue/composition-api';
import { EXPORT_MAX_COUNT } from '@/common';
import { useMessage } from './uesMessage';
import { formatTime } from '@/utils';

function handleDataExport(data, fileName) {
  const fileReader = new FileReader();
  fileReader.readAsDataURL(data);
  fileReader.onload = (event) => {
    // 处理load事件。该事件在读取操作完成时触发
    // 新建个下载的a标签，完成后移除。
    const a = document.createElement('a');
    a.download = `${fileName}报表${formatTime(new Date(), 'YYYYMMDDHHMM')}.xls`;
    a.href = event.target?.result;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };
}

/**
 * @desc 文件导出hooks
 * @author lllwx
 * @date 2021/12/1 2:11 下午
 * @return
 */
export function useExport(exportService, options, form) {
  const { createMessage } = useMessage();
  const baseOptions = {
    maxCount: EXPORT_MAX_COUNT,
    count: 0,
    title: '',
  };
  const exportOptions = ref({
    ...baseOptions,
    title: unref(options.title) || '',
  });

  // 当前数据量会动态改变
  watch(() => options.count.value, (value) => {
    exportOptions.value.count = value;
  });
  // 导出文件标题可以是ref，动态改变文件名称
  if (isRef(options.title)) {
    watch(() => options.title.value, (value) => {
      exportOptions.value.title = value;
    });
  }

  const isExportLoading = ref(false);

  const handleExport = async () => {
    // 是否设置了最大导出数量
    if (exportOptions.value.maxCount) {
      if (exportOptions.value.count > exportOptions.value.maxCount) {
        createMessage.warning('导出数据量过大，请缩小筛选范围');
        return;
      }
    }
    if (!exportOptions.value.count) {
      createMessage.warning('暂无导出数据');
      return;
    }
    isExportLoading.value = true;
    try {
      const { data } = await exportService(form);
      handleDataExport(data, exportOptions.value.title);
      createMessage.success('导出成功');
    } finally {
      isExportLoading.value = false;
    }
  };

  return {
    isExportLoading,
    handleExport,
  };

}
